package servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.ISong;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;

import dao.ISongDAO;

/**
 * @web.servlet name="songServlet"
 * @web.servlet-mapping url-pattern="/auth/music/*"
 * @author ipeel
 *
 */
public class SongServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String mimeType = "audio/mpeg";
		ISongDAO songService = (ISongDAO)WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()).getBean("SONG_SERVICE");
		Integer songId = new Integer(request.getParameter("songId"));
		ISong song = songService.getSongById(songId);
		File file = new File(song.getPath());
		InputStream is = new FileInputStream(file);
	    
        // Get the size of the file
        long length = file.length();
    
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];
    
        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
               && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
        }
    
        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }
    
        // Close the input stream and return bytes
        is.close();
    	
    	response.setContentLength(bytes.length);
    	response.setContentType(mimeType);
    	FileCopyUtils.copy(bytes , response.getOutputStream());
	}

}
